﻿Imports Microsoft.AspNet.Identity
Imports System
Imports System.Collections.Generic
Imports System.Web.Security

Public Class Manage
    Inherits System.Web.UI.Page
    Public Property SuccessMessageText() As String
        Get
            Return m_SuccessMessage
        End Get
        Private Set(value As String)
            m_SuccessMessage = value
        End Set
    End Property
    Private m_SuccessMessage As String

    Public Property CanRemoveExternalLogins() As Boolean
        Get
            Return m_CanRemoveExternalLogins
        End Get
        Private Set(value As Boolean)
            m_CanRemoveExternalLogins = value
        End Set
    End Property
    Private m_CanRemoveExternalLogins As Boolean

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            ' Determine the sections to render
            Dim localUserName As String = IdentityConfig.Logins.GetProviderKey(User.Identity.GetUserId(), IdentityConfig.LocalLoginProvider)
            If localUserName IsNot Nothing Then
                changePasswordHolder.Visible = True
                changePasswordUserName.Text = localUserName
            Else
                setPassword.Visible = True
                changePasswordHolder.Visible = False
            End If
            CanRemoveExternalLogins = IdentityConfig.Logins.GetLogins(User.Identity.GetUserId()).Count > 1

            ' Render success message
            Dim message = Request.QueryString("m")
            If message IsNot Nothing Then
                ' Strip the query string from action
                Form.Action = ResolveUrl("~/Account/Manage")

                Select Case message
                    Case "ChangePwdSuccess"
                        SuccessMessageText = "Your password has been changed."
                    Case "SetPwdSuccess"
                        SuccessMessageText = "Your password has been set."
                    Case "RemoveLoginSuccess"
                        SuccessMessageText = "The external login was removed."
                    Case Else
                        SuccessMessageText = String.Empty
                End Select

                successMessage.Visible = Not String.IsNullOrEmpty(SuccessMessageText)
            End If
        End If
    End Sub

    Protected Sub changePassword_Click(sender As Object, e As EventArgs)
        If IsValid Then
            Dim loginInfo As UserSecret = TryCast(IdentityConfig.Secrets.Find(changePasswordUserName.Text), UserSecret)
            If loginInfo Is Nothing Then
                FailureText.Text = "Error finding user"
                Return
            End If
            If Not IdentityConfig.Secrets.Validate(changePasswordUserName.Text, CurrentPassword.Text) Then
                FailureText.Text = "Current password does not match"
                Return
            End If
            If IdentityConfig.Secrets.UpdateSecret(changePasswordUserName.Text, NewPassword.Text) Then
                Response.Redirect("~/Account/Manage?m=ChangePwdSuccess")
            Else
                FailureText.Text = "Change password failed"
            End If
        End If
    End Sub


    Protected Sub setPassword_Click(sender As Object, e As EventArgs)
        If IsValid Then
            ' Create the local login info and link the local account to the user
            Dim userName As String = User.Identity.GetUserName()
            If IdentityConfig.Secrets.Create(New UserSecret(userName, password.Text)) AndAlso IdentityConfig.Logins.Add(New UserLogin(User.Identity.GetUserId(), IdentityConfig.LocalLoginProvider, userName)) Then
                Response.Redirect("~/Account/Manage?m=SetPwdSuccess")
            Else
                FailureText.Text = "Failed to set password"
            End If
        End If
    End Sub

    Public Function GetLogins() As IEnumerable(Of IUserLogin)
        Dim accounts = IdentityConfig.Logins.GetLogins(User.Identity.GetUserId())
        CanRemoveExternalLogins = accounts.Count > 1
        Return accounts
    End Function

    Public Sub RemoveLogin(loginProvider As String, providerKey As String)
        Dim m = If(IdentityConfig.Logins.Remove(User.Identity.GetUserId(), loginProvider, providerKey), "?m=RemoveLoginSuccess", [String].Empty)
        If loginProvider = IdentityConfig.LocalLoginProvider Then
            ' Need to delete local user if we are unlinking that
            IdentityConfig.Secrets.Delete(providerKey)
        End If
        Response.Redirect("~/Account/Manage" & m)
    End Sub


End Class